import { useHistory } from 'react-router-dom'
import { NavBar, InfiniteScroll } from 'antd-mobile'

import styles from './index.module.scss'
import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getResults, clearResults } from '@/store/actions/search'
import { RootState } from '@/types/store'
import ArticleItem from '@/pages/Home/components/ArticleItem'

const Result = () => {
  const history = useHistory()
  const param = new URLSearchParams(history.location.search)
  const keyword = param.get('key');
  const dispatch = useDispatch()
  const pageRef = useRef(1);

  useEffect(() => {
    return () => {
      dispatch(clearResults())
    }
  }, [dispatch])

  const {results, total_count} = useSelector((state: RootState) => state.search.result);

  const loadMore = async () => {
    await dispatch(getResults(keyword!, pageRef.current))
    pageRef.current = pageRef.current + 1
  }

  const hasMore = results.length < total_count

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {
          results.map((article) => (
            <ArticleItem article={article}/>
          ))
        }
        <InfiniteScroll hasMore={hasMore} loadMore={loadMore}/>
      </div>
    </div>
  )
}

export default Result
